const cheerio = require("cheerio")
const fs = require("fs")
const https = require("https")
const path = require("path")



// 加载html页面
const html = fs.readFileSync("./home.html", "utf-8")
// console.log(html)

// 获取jq对象
const $ = cheerio.load(html)

// 获取图片数组
let imgArr = $("#primary-home img").toArray().map(item => item.attribs["data-src"])

// 遍历数组并写入./img文件夹中 
imgArr.forEach((item, index) => {
    https.get(item, function (resp) {
        // console.log(item)
        console.log("请求url: " + resp.url, " :正在请求中")
        resp.setEncoding("binary")
        let imgData = ""
        resp.on("data", (chunk) => {
            imgData += chunk
        })
        resp.on("end", () => {
            let imgPath = path.join(__dirname, "./img/", path.basename(item)) 
            fs.writeFile(imgPath, imgData, "binary", (e) => {
                if (e) {
                    console.log("请求url: " + resp.url, " :写入失败")
                } else {
                    console.log("请求url: " + resp.url, " :写入成功: " + imgPath)
                }
            })
        })
    })
})


